<template>
  <div>
    <van-nav-bar left-arrow @click="leftClick"></van-nav-bar>
    <div class="login-form">
      <h3 class="title">短信登录</h3>
      <van-form ref="form">
        <van-field
          name="mobile"
          v-model="form.mobile"
          :rules="rules.mobile"
          placeholder="请输入手机号"
        ></van-field>

        <van-field
          v-model="form.code"
          :rules="rules.code"
          placeholder="请输入验证码"
        >
          <template #button>
            <div class="code code1" @click="sendCode" v-if="totalTime === 6">
              发送验证码
            </div>
            <div class="code code2" v-else>{{ totalTime }}秒后再试</div>
          </template>
        </van-field>
        <van-button class="btn" @click="submit">登录</van-button>
      </van-form>
    </div>
  </div>
</template>

<script>
import { anthorizations, smsCodes } from "@/api/user.js";
export default {
  data() {
    return {
      form: {
        mobile: "",
        code: ""
      },
      totalTime: 6,
      interval: "",
      rules: {
        mobile: [
          { required: true, message: "必填", trigger: "onChange" },
          {
            validator: value => {
              const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              return reg.test(value);
            },
            message: "请输入正确手机号",
            trigger: "onChange"
          }
        ],
        code: [
          { required: true, message: "必填", trigger: "onChange" },
          {
            validator: value => {
              return value.length === 6;
            },
            message: "请输入6位验证码",
            trigger: "onChange"
          }
        ]
      }
    };
  },
  methods: {
    leftClick() {},
    // 发送验证码方法
    sendCode() {
      this.$refs.form
        // validate 里面传参 是验证传参的内容
        .validate("mobile")
        .then(async () => {
          this.totalTime--;
          this.interval = setInterval(() => {
            this.totalTime--;
            if (this.totalTime <= 0) {
              clearInterval(this.interval);
              this.totalTime = 6;
            }
          }, 1000);

          await smsCodes(this.form.mobile);

          // success 成功
          this.$toast.success("发送验证码成功");
        });
    },

    // 登录方法
    submit() {
      this.$refs.form
        // validate 没穿参 是全局验证
        .validate()
        // then 成功
        .then(async () => {
          //loading加载弹窗
          this.$toast.loading({ duration: 0 });
          // await异步转同步(await所在的函数前面要加async) 获取form的数据
          const res = await anthorizations(this.form);
          // 存储token到vuex中 commit
          this.$store.commit("user/setToken", res.data.token);
          // 存储refrech_token
          this.$store.commit('user/setRefreshToken', res.data.refresh_token)
          // 登录成功直接跳转到首页
          // this.$router.push("/");
          const redirect = this.$route.query.redirect || "/";
          console.log("redirect:", redirect);
          this.$router.push(redirect);

          // success弹窗
          this.$toast.success("验证成功");
        })
        // catch失败
        .catch(() => {
          this.$toast.fail("验证失败");
        });
    }
  },
  beforeDesthroy() {
    // 组件销毁时，清除定时器，释放内存
    clearInterval(this.interval);
  }
};
</script>

<style lang="less" scoped>
.code1 {
  color: green !important;
}

.code2 {
  color: red !important;
}

::v-deep .van-nav-bar .van-icon {
  color: #999;
}
.login-form {
  padding: 20px;
}
.title {
  font-size: 18px;
  font-weight: 400;
  padding-left: 15px;
}
.code {
  font-size: 14px;
  color: #ccc;
}
.btn {
  width: 100%;
  background-color: #fd514a;
}
</style>
